package com.fenrirtec.aepp.manage.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fenrirtec.aepp.manage.common.definition.Definition;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class LoginCheckInterceptor extends AbstractInterceptor {
	
	private static final long serialVersionUID = 1L;

	private static final Logger logger = LoggerFactory.getLogger(LoginCheckInterceptor.class);
	
	private static final String TIMEOUT = "timeout";

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
	    HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		HttpServletResponse response = ServletActionContext.getResponse();

		if (session == null || session.getAttribute(Definition.SessionKey.USER_INFO) == null) {
			if (logger.isDebugEnabled()) {
				logger.debug("user does not login.");
			}
			if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
			    response.setHeader("sessionstatus", "timeout");
			    response.setHeader("Content-type", "text/html;charset=UTF-8");
			    response.setCharacterEncoding("UTF-8");
                response.getWriter().print("timeout");
			    return invocation.invoke();
			}
			return TIMEOUT;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("user already login. session=" + session);
			}
			return invocation.invoke();
		}
	}
}
